package cn.laixueit.controller;

import cn.laixueit.pojo.OrderDetail;
import cn.laixueit.pojo.OrderVo;
import cn.laixueit.pojo.ShipAddress;
import cn.laixueit.service.ShipAddressService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class ShipAddressController {

    @Autowired
    private ShipAddressService shipAddressService;

    @PostMapping("/createOrder")
    @ApiOperation(value = "创建订单",notes = "根据当前用户创建于一个订单")
    @ApiImplicitParams(@ApiImplicitParam(name = "map",value = "传递的订单数据，包含商品列表，收货人信息等等"))
    @ApiResponses(@ApiResponse(code = 200,message = "返回订单号"))
    public ResponseEntity<String> createOrder(@RequestBody OrderVo orderVo){
        String orderId = shipAddressService.createOrder(orderVo);
        return ResponseEntity.ok(orderId);
    }


    @GetMapping("/findAllAddress")
    @ApiOperation(value = "查询当前用户的所有收货地址",notes = "查询收货地址,当前用户通过token进行获取")
    public ResponseEntity<List<ShipAddress>> findAll(@CookieValue("leyouToken")String token){
        List<ShipAddress> addressList = shipAddressService.listByUser(token);
        return ResponseEntity.ok(addressList);
    }

    @GetMapping("/findAllOrder")
    @ApiOperation(value = "查询当前用户的所有未支付订单",notes = "查询收货地址,当前用户通过token进行获取")
    public ResponseEntity<List<OrderDetail>> findAllOrder(String orderId){
        List<OrderDetail> orderDetailList = shipAddressService.listOrderDetail(orderId);
        return ResponseEntity.ok(orderDetailList);
    }

    @PostMapping("/subOrder")
    @ApiOperation(value ="提交订单，补全订单信息")
    public ResponseEntity<Void> subOrder(@RequestBody ShipAddress shipAddress){
        shipAddressService.subOrder(shipAddress);
        return ResponseEntity.status(HttpStatus.OK).build();
    }

    @GetMapping("/alipay/{orderId}")
    public ResponseEntity<Void> alipay(@PathVariable String orderId,HttpServletRequest request,HttpServletResponse response){
        try {
            doPost(request,response,orderId);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.OK).build();
    }

    private String CHARSET = "UTF-8";
    private String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCgfa8SAMEhWpJNDHULCK9zC1AZfMBjs+PRfGm0V/pI78exSGxc8r+ZhsXFvHxoUFquIEsUYLwbkg0hkso+HmQDYheSxiMzIIy7sLvzqL/eQMg5w7MjWbr0PPqtBDBnigXLa8lEFTU9SbLhGoork6eQE60T79u+h8S1jjwnwIu7SlGwlaIfMyZl+bsfWEpIfN2rG6FAhZJSmWE94KqsTfE8C3kzO9CnKHwS0ms44lVIbsg8JIzU+22UMBPgjz5l86KkMDreJ3CHE6FJj2gcq7NwqT86UoFYaS6aDL3EqNeBEGhtMim/mFi1YkvCOU+U2+wPyqd4xOrDTon9X28vFX6rAgMBAAECggEAJDnab5zd+zJffabHMJNoTvaJwQcIwjiTvvBvR7boFtiQ4bJwS1a76uKh961BA6bHoTBG4jWnoC2Kaz6gCf+AIcddfNLelSbOvXr6IdjAXmGPEILdB6i0a3bsOmuMpYJhJnaQ+p4y4z+kce00rPtqQjo+whZNKqeovjZ525s5ry+OyuldzV0J/q3vQGSYaEN8ba4PNGhnczjlAMhT3LGLZnhiiq4lUvLu4fxMeHxfSo1h4T9nu6sufSIHE37aCk1TZ5RGq0pP8nf+DKY9hFjzEcuPOtFA36AIt13hlnyUtr68mvez75571Y/6S8L/L+tCIVIOfld5SOUStuwEjMAWOQKBgQDR6hCi6ZFclE9WFVcZsN4+h93/7ftPKHpoouX5t6Ns0R51o33uI9IJsMZ42XkpdaeWPgWMyDCLoxibE5C5q5Xilv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BzeTXA2l/2+yuIeX1xOcfnWtmLVUfcshU4bpTDGmFu4WNiiynmjLrm0RegVVap2xDljwxFc7SqLzzvxJCGV8jnLuN6NN/OhpuTBW6DlzSaQIDAQAB";

    public void doPost(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse,String orderId) throws ServletException, IOException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016091300503130", APP_PRIVATE_KEY, "json",
                CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":\"+"+orderId+"+\"," +
                " \"total_amount\":\"88.88\"," +
                " \"subject\":\"Iphone6 16G\"," +
                " \"product_code\":\"QUICK_WAP_WAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

}
